package edu.xjdx.os.domain;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class Verification {

    private static char randomChar() {
        String string = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random = new Random();
        return string.charAt(random.nextInt(string.length()));
    }

    public static String drawImage(HttpServletResponse response) {
        //1.拼接字符串的类
        StringBuilder builder = new StringBuilder();
        //产生4位验证码
        for (int i = 0; i < 4; i++) {
            builder.append(randomChar());
        }
        String code = builder.toString();
        //2.定义图片的宽度和高度
        int width = 120;
        int height = 25;
        //建立BufferedImage对象，指定图片缓冲流的长宽度和样式
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        //3.获取Graphics2d绘制对象，开始绘制验证码。图片最终会注入到缓冲流中
        Graphics2D graph = bi.createGraphics();
        //4.设置字体和大小
        Font font = new Font("宋体", Font.PLAIN, 20);
        Color color = new Color(0, 255, 255);
        graph.setFont(font);
        graph.setColor(color);
        graph.setBackground(new Color(0, 0, 0));
        //绘制形状，一般是矩形
        graph.clearRect(0, 0, width, height);
        //创建字体对象
        FontRenderContext context = graph.getFontRenderContext();
        //获得文字的边界
        Rectangle2D bounds = font.getStringBounds(code, context);
        //计算坐标和间距，以便字体放在矩形的正中央
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double acsent = bounds.getY();
        double baseY = y - acsent;
        //在矩形中绘制字体
        graph.drawString(code, (int) x, (int) baseY);
        graph.dispose();
        //保存到响应的输出流
        try {
            ImageIO.write(bi, "jpg", response.getOutputStream());
            //刷新响应流
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //用于验证码的对比和存储
        return code;

    }



}
